package common.inter;

import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;

import common.kit.IpKits;
import model.User;
import service.LoginService;

/**
 * 用户登录权限拦截
 * @author phooob
 *
 */
public class AdminLoginInter implements Interceptor{

	@Inject
    private LoginService loginService;

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        String sessionId = controller.getRequest().getHeader("token") ;
        if (StrKit.isBlank(sessionId)) {
			sessionId = controller.getPara("token");
		}
        if (StrKit.isBlank(sessionId)) {
        	 controller.renderJson(Ret.fail("state" , "needLogin"));
             return;
		}
        User loginUser = CacheKit.get(LoginService.loginUserCacheName, sessionId);
        if (loginUser == null) {
            String loginIp = IpKits.getRealIp(controller.getRequest());
            loginUser = loginService.loginWithSessionId(sessionId, loginIp);
        }

        if ( null == loginUser || loginUser.getIsDelete()) {
        	loginService.logout(sessionId);
        	controller.renderJson(Ret.fail("state" , "needLogin"));
            return;
		}

        //将用户登录账号传递到模块处理页面,供模板引擎使用
        controller.setAttr(LoginService.loginUserCacheName, loginUser);
        inv.invoke();
        controller.removeAttr(LoginService.loginUserCacheName);
        
    }

}
